package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/go-sql-driver/mysql"
	"github.com/gookit/event"
	"github.com/vueadmin/global"
	e "github.com/vueadmin/utils/exception"
	"github.com/vueadmin/utils/response"
	"go.uber.org/zap"
	"net/http"
)

// 异常捕获
func GinRecovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				switch err.(type) {
				//mysql错误异常
				case *mysql.MySQLError:
					event.MustFire("exceptionLogEvent", event.M{
						"errMsg": err.(*mysql.MySQLError).Error(),
						"handle": c,
					})
					response.FailWithCode(c, http.StatusInternalServerError, err.(*mysql.MySQLError).Error())
				case e.ValidateError:
					response.Fail(c, err.(e.ValidateError).Error())
				case e.ValidateWithCodeError:
					response.FailWithCode(c, err.(e.ValidateWithCodeError).Code, err.(e.ValidateWithCodeError).Msg)
				default:
					setLog(err, c)
					response.FailWithCode(c, http.StatusInternalServerError, "系统错误")
				}
				c.Abort()
				return
			}
		}()

		c.Next()
	}
}

// 写入日志
func setLog(err any, c *gin.Context) {
	global.LOG.Error("[Recovery from panic]",
		zap.Any("error", err),
		zap.String("request", c.Request.Method),
		zap.String("request", c.Request.RequestURI),
	)
}
